# Create your views here.
#from django.shortcuts import render_to_response
#from google.appengine.ext import ndb
#def home(request):
#	return render_to_response('gold-builder/gold-builder.html')

from django.http import HttpResponse
from django.template import RequestContext, loader
from google.appengine.ext import ndb
from goldbuilder.models import GoldData
from goldbuilder.models import Dataset
import csv
import string
import random
import json

def home(request):

	base_url_img = '/static/goldbuilder/img/82/'
	instanceId = request.GET.get('instanceId', '');


	#We randomly switch the gold to be first or second in the corresponding web page.
	if random.random() >= 0.5:
		taskId1 = request.GET.get('taskId1', '')
		taskImg1 = base_url_img + taskId1 + '.png'
		taskId2 = request.GET.get('taskId2', '')
		taskImg2 = base_url_img + taskId2 + '.png'
	else:
		taskId1 = request.GET.get('taskId2', '')
		taskImg1 = base_url_img + taskId1 + '.png'
		taskId2 = request.GET.get('taskId1', '')
		taskImg2 = base_url_img + taskId2 + '.png'


	template = loader.get_template('goldbuilder/goldbuilder.html')
	context = RequestContext(request, {
		'instanceId': instanceId,
		'taskImg1': taskImg1,
		'taskId1': taskId1,
		'taskImg2': taskImg2,
		'taskId2': taskId2,
		'processId': 82
		})
	return HttpResponse(template.render(context))

	
def submitLabel(request):

	instanceId = int(request.GET.get('instanceId', 0))
	processId = int(request.GET.get('processId', 0))
	taskId1 = int(request.GET.get('taskId1', 0))
	proposedLabel1 = request.GET.get('proposedLabel1', '')
	taskId2 = int(request.GET.get('taskId2', 0))
	proposedLabel2 = request.GET.get('proposedLabel2', '')


	

	# We search for the instance and get the taskId that plays as "gold"
	qry = Dataset.query(Dataset.instanceId == instanceId)
	taskIdGold = 0
	for d in qry:
		taskIdGold = d.taskIdGold


	token = ''.join(random.SystemRandom().choice(string.ascii_uppercase) for _ in range(3)) + ''.join(random.SystemRandom().choice(string.digits) for _ in range(3))

	proposedLabel = ""
	taskIdNotGold = 0
	proposedLabelNotGold = ""

	if taskIdGold == taskId1:
		proposedLabel = proposedLabel1
		taskIdNotGold = taskId2
		proposedLabelNotGold = proposedLabel2
	else:
		proposedLabel = proposedLabel2
		taskIdNotGold = taskId1
		proposedLabelNotGold = proposedLabel1



	goldNeeded = False
	goldMet = False



	# If we have a gold in the instance, we go and get its token if the worker provided an accepted name for the activity
	qry = GoldData.query(ndb.AND(GoldData.processId == processId, GoldData.taskId == taskIdGold))
	for g in qry:
		goldNeeded = True
		if g.proposedLabel.lower().replace(" ", "") == proposedLabel.lower().replace(" ", ""):
			goldMet = True
			token = g.token
			break	

	gold = GoldData()
	gold.experimentId = "1"
	gold.processId = processId
	gold.taskId = taskIdNotGold
	gold.originalLabel = ""
	gold.proposedLabel = proposedLabelNotGold
	gold.default = 0
	gold.token = token
	gold.put()

	resp = {}
	resp['token'] = token;
	resp['goldNeeded'] = goldNeeded
	resp['goldMet'] = goldMet

	return HttpResponse(json.dumps(resp), content_type="application/json")


def goldData(request):

	dic = {}

	qry = GoldData.query()
	for g in qry:
		dic[g.proposedLabel] = g.proposedLabel

	lst = '['	
	for key in dic.keys():
		lst = lst + '"' + key + '",'
	
	lst = lst.rstrip(",") #delete trailing comma
	lst = lst + "]"

	return HttpResponse(lst)

def loadCsvFiles(request):

	qry = GoldData.query()
	for g in qry:
		g.key.delete()

	with open('private/gold_data.csv', 'rb') as csvfile:
		reader = csv.DictReader(csvfile, delimiter=';', quotechar='"')
		for row in reader:
			gold = GoldData()
			gold.experimentId = row['experimentId']
			gold.processId = int(row['processId'])
			gold.taskId = int(row['taskId'])
			gold.originalLabel = row['originalLabel']
			gold.proposedLabel = row['proposedLabel']
			gold.default = int(row['default'])
			gold.token = row['token']
			gold.put()
			

	qry = Dataset.query()
	for d in qry:
		d.key.delete()

	with open('private/dataset.csv', 'rb') as csvfile:
		reader = csv.DictReader(csvfile, delimiter=';', quotechar='"')
		for row in reader:
			dataset = Dataset()				
			dataset.instanceId = int(row['instanceId'])
			dataset.taskId1 = int(row['taskId1'])
			dataset.taskId2 = int(row['taskId2'])
			dataset.label1 = row['label1']
			dataset.label2 = row['label2']
			dataset.token = row['token']
			
			if row['taskIdGold'] != "":
				dataset.taskIdGold = int(row['taskIdGold'])

			dataset.put()
			
			

	return HttpResponse("OK")


def downloadResults(request):
	qry = GoldData.query()
	lst = "experimentId,processId,taskId,originalLabel,proposedLabel,default,token<br/>"
	for g in qry:
		lst = lst + str(g.experimentId) + "," + str(g.processId) + "," + str(g.taskId)+ "," + g.originalLabel + "," + g.proposedLabel +  "," + str(g.default) + "," + g.token + "<br/>"

	return HttpResponse(lst)



